/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.pojo.base;

import org.openislands.oi.util.ValueCopyUtils;

import java.util.function.Consumer;

public class BeanBuilder<E> {
    private final E element;

    public BeanBuilder(E element) {
        this.element = element;
    }

    public BeanBuilder<E> set(Consumer<E> consumer) {
        consumer.accept(this.element);
        return this;
    }

    public <V> BeanBuilder<E> set(SetBuilder<E, V> set, V value) {
        set.set(this.element, value);
        return this;
    }

    public <V> V get(GetBuilder<E, V> get) {
        return get.get(this.element);
    }

    public E build() {
        return this.element;
    }

    public <T> T build(T target) {
        return ValueCopyUtils.copyProperties(this.build(), target);
    }

    public <T> T build(Class<T> targetClass) {
        return ValueCopyUtils.copyProperties(this.build(), targetClass);
    }

    public <T> BeanBuilder<T> convert(T target) {
        return BeanBuilder.create(ValueCopyUtils.copyProperties(this.build(), target));
    }

    public <T> BeanBuilder<T> convert(Class<T> targetClass) {
        return BeanBuilder.create(ValueCopyUtils.copyProperties(this.build(), targetClass));
    }

    public static <E> BeanBuilder<E> create(E element) {
        return new BeanBuilder<>(element);
    }

    public interface SetBuilder<E, V> {
        /***
         * (element, value) -> {}
         * @param element obj
         * @param value   obj field value
         */
        void set(E element, V value);
    }

    public interface GetBuilder<E, V> {
        /***
         * (element) -> value
         * @param element handle target
         * @return obj field value
         */
        V get(E element);
    }
}
